import React from "react";
import { connect } from "react-redux";
import {
  Form,
  Select,
  Input,
  Row,
  Col,
  InputNumber,
  Spin,
  message,
  Button,
  Alert,
  Icon,
  Popover,
} from "antd";
import "styles/loan-billing/repayment-content.scss";
import { messages, deepFullCopy } from "share/common";
import ImageUpload from "components/image-upload";
import moment from "moment";
import DiDiService from "./didi-expense.service";

const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14, offset: 1 },
};

class NewRepayment extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      info: {},
      paymentType: "cash",
      repayAttachment: [],
      repayAttachmentImages: [],
      loading: false,
      loanRefund: false,
      printLoading: false,
      allSelectedRecords: [],
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.repayFrame === this.props.repayFrame) return;
    if (!nextProps.repayFrame) {
      this.props.form.resetFields();
      this.setState({
        info: {},
        repayAttachment: [],
        repayAttachmentImages: [],
        loanRefund: false,
        allSelectedRecords: [],
      });
      return !1;
    }
    this.props.form.resetFields();
    const { isOldCompany } = this.props;
    this.setState({
      info: nextProps.info,
      loanRefund: nextProps.loanRefund,
      allSelectedRecords: nextProps.allSelectedRecords,
    });
  }

  /**
   * 格式化数字
   * @param {Number} nStr 数字
   */
  addCommas = (nStr) => {
    nStr = nStr + "";
    let x = nStr.split(".");
    let x1 = x[0];
    let x2 = x.length > 1 ? "." + x[1] : "";
    let rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, "$1" + "," + "$2");
    }
    return x1 + x2;
  };

  //获取上传图片的OId
  getUploadImageOId = (values) => {
    let repayAttachment = [];
    values.map((item) => {
      repayAttachment.push({ attachmentOID: item.attachmentOID });
    });
    this.setState({ repayAttachment, repayAttachmentImages: values });
  };

  /**
   * 提交还款单
   * @param {Boolean} isNeedPrint 是否需要打印
   */
  handleSave = async (isNeedPrint = false) => {
    this.props.form.validateFieldsAndScroll(async (err, values) => {
      if (!err) {
        let repayAttachmentOids = this.state.repayAttachment.map(
          (item) => item.attachmentOID
        );
        let paramsBody = {
          ids: [],
          relations: this.props.params.params.relations,
          repayAttachmentOids: repayAttachmentOids,
          remark: values.remark,
        };
        const { agentOid } = this.props.params;
        let paramsUrl = {
          print: isNeedPrint,
          companyName: "金拱门(中国)有限公司(公司编码:104)",
          accountName: "金拱门(中国)有限公司",
        };
        this.setState(
          {
            loading: true,
          },
          async () => {
            let res = await DiDiService.toBorrow(paramsBody, paramsUrl);
            if (res.status === 200) {
              message.success("操作成功");
              this.setState({ loading: false });
              this.props.submitFun();
            } else {
              console.error(res);
              this.setState({ loading: false });
              message.error("操作失败，请重新操作。");
            }
          }
        );
      }
    });
  };

  hanldeOnViewDetails = (record, index) => {
    let tempRecords = deepFullCopy(this.state.allSelectedRecords);
    if (tempRecords[index].id === record.id) {
      if (
        tempRecords[index].selectedRelationList &&
        tempRecords[index].selectedRelationList.length > 0
      ) {
        tempRecords[index].showDetails = !record.showDetails;
      }
    } else {
      tempRecords.some((item, i) => {
        if (item.id === record.id) {
          if (
            tempRecords[i].selectedRelationList &&
            tempRecords[i].selectedRelationList.length > 0
          ) {
            tempRecords[i].showDetails = !record.showDetails;
            return true;
          }
        }
      });
    }
    this.setState({
      allSelectedRecords: tempRecords,
    });
  };

  render() {
    const {
      repayAttachmentImages,
      loading,
      loanRefund,
      allSelectedRecords,
    } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="new-repayment-frame">
        {!loanRefund && (
          <Alert
            type="warning"
            showIcon
            style={{ marginBottom: "8px" }}
            message={
              messages(
                "loan-billing.key154"
              ) /*还款单提交后，还需财务复核方可生效*/
            }
          />
        )}
        <Form>
          <div className="title">
            {messages("loan-billing.key72") /*还款方信息*/}
          </div>
          <Row>
            <Col span={6} className="form-define-title">
              {messages("loan-billing.key7") /*还款金额*/}：
            </Col>
            <Col span={3} offset={1}>
              <FormItem>
                {getFieldDecorator("curreny", {
                  initialValue: "CNY",
                })(<Input disabled />)}
              </FormItem>
            </Col>
            <Col span={5}>
              <FormItem>
                {getFieldDecorator("repaymentValue", {
                  rules: [],
                  initialValue: this.addCommas(
                    Number(this.props.total || "0").toFixed(2)
                  ),
                })(<Input min={0} className="input-number" disabled />)}
              </FormItem>
            </Col>
          </Row>
          <FormItem
            {...formItemLayout}
            label={messages("loan-billing.key3") /*还款方式*/}
            className={"paymentType-select"}
          >
            {getFieldDecorator("paymentType", {
              rules: [],
              initialValue: "online",
            })(
              <Select
                disabled
                getPopupContainer={() =>
                  document.getElementsByClassName("paymentType-select")[0]
                }
              >
                <Option key={"online"} value={"online"}>
                  转账还款
                </Option>
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label={messages("common.remark") /*备注*/}
          >
            {getFieldDecorator("remark", {
              rules: [
                {
                  required: true,
                  message: messages("common.enter"),
                },
              ],
              initialValue: "滴滴消费转因私",
            })(
              <TextArea
                rows={4}
                style={{ width: "100%", resize: "none" }}
                maxLength="200"
                disabled
                placeholder={`${messages(
                  "common.please.enter"
                )}, ${messages("common.max.characters.length", { max: 200 })}`}
              />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label={`${messages("loan-billing.key79") /*流水转账凭证*/
              }（${messages("common.max.image.length", { max: 3 })}）`}
          >
            {getFieldDecorator("repayAttachment", {
              rules: [
                {
                  required: true,
                  message: messages("common.please.select"),
                },
              ],
              initialValue: [],
            })(
              <ImageUpload
                attachmentType="REPAYMENT_IMAGES"
                defaultFileList={repayAttachmentImages}
                fileType={[
                  "PNG",
                  "png",
                  "JEPG",
                  "jepg",
                  "jpg",
                  "JPG",
                  "bmp",
                  "BMP",
                  "jpg",
                  "JPG",
                  "jpeg",
                  "JPEG",
                ]}
                isShowDefault
                maxNum={3}
                onChange={this.getUploadImageOId}
              />
            )}
          </FormItem>
          <div>
            <div className="title">
              {" "}
              {messages("loan-billing.key80") /* 收款方信息 */}
              <span>
                {messages("loan-billing.key81") /* 请按以下收款方账号打款 */}
              </span>
            </div>
            <FormItem
              {...formItemLayout}
              label={messages("loan-billing.key186") /* 开户公司 */}
              className="accept-account-container"
            >
              {getFieldDecorator("companyName", {
                rules: [],
                initialValue: "104",
              })(
                <Select disabled placeholder={messages("common.please.select")}>
                  <Option key={"104"} value={"104"}>
                    金拱门(中国)有限公司
                  </Option>
                </Select>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={messages("loan-billing.key76") /*开户账号*/}
            >
              {getFieldDecorator("acceptAccount", {
                initialValue: "2116 8111 4610 001",
              })(<Input disabled />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={messages("loan-billing.key188") /*账号名称*/}
            >
              {getFieldDecorator("accountName", {
                initialValue: "金拱门(中国)有限公司",
              })(<Input disabled />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={messages("loan-billing.key77") /*开户银行*/}
            >
              {getFieldDecorator("acceptBankName", {
                initialValue: "招商银行股份有限公司上海苏河湾支行",
              })(<Input disabled />)}
            </FormItem>
          </div>
          <div>
            <div className="title">{"滴滴消费明细"}</div>
            <div
              className="detailsContainer"
              style={{ padding: "0px", marginLeft: "1px" }}
            >
              {allSelectedRecords.map((record, index) => {
                if (
                  record.selectedRelationList &&
                  record.selectedRelationList.length > 0
                ) {
                  let total = 0;
                  let oriTotal = 0;
                  record.selectedRelationList.map((item) => {
                    if (Number(item.amount) !== NaN) {
                      total = total + item.amount;
                    }
                    if (Number(item.oriAmount) !== NaN) {
                      oriTotal = oriTotal + item.oriAmount;
                    }
                  });
                  return (
                    record.selectedRelationList.length > 0 && (
                      <div className={"detailBlock"}>
                        <div
                          style={{ fontSize: "12px" }}
                          className={"detailHead"}
                        >
                          <div className="didiDetails">
                            <span className={"headText"}>交易金额：</span>
                            <span className={'headText'}>{'CNY'}</span>
                            <span className={'headText'}>{this.addCommas(Number(record.actualPrice || '0').toFixed(2))}</span>
                          </div>
                          <div className="didiDetails">
                            <span className={"headText"}>交易日期：</span>
                            <span className={"headText"}>
                              {record.payTime
                                ? moment(record.payTime).format("YYYY-MM-DD")
                                : "-"}
                            </span>
                          </div>
                          <div className="didiDetails">
                            <span className={"headText"}>上车时间：</span>
                            <span className={"headText"}>
                              {record.departureTime
                                ? moment(record.departureTime).format(
                                  "YYYY-MM-DD HH:mm:ss"
                                )
                                : "-"}
                            </span>
                            <span
                              style={{ marginRight: "5px", marginLeft: "5px" }}
                            >
                              |
                            </span>
                            <span className={"headText"}>下车时间：</span>
                            <span className={"headText"}>
                              {record.finishTime
                                ? moment(record.finishTime).format("YYYY-MM-DD HH:mm:ss")
                                : "-"}
                            </span>
                          </div>
                          <div className="didiDetails">
                            <span className={"headText"}>上车地点：</span>
                            <span className={"headText"}>
                              {record.actualStartName}
                            </span>
                          </div>
                          <div className="didiDetails">
                            <span className={"headText"}>下车地点：</span>
                            <span className={"headText"}>
                              {record.actualEndName}
                            </span>
                          </div>
                        </div>
                      </div>
                    )
                  );
                }
              })}
            </div>
          </div>
        </Form>
        <div
          className="footer-operate"
          style={{
            backgroundColor: "#ffffff",
            left: "0px",
            marginRight: "10px",
          }}
        >
          <Button
            type="primary"
            onClick={() => this.handleSave()}
            style={{ marginRight: "10px" }}
            loading={loading}
          >
            {
              loanRefund
                ? messages("loan-billing.key83") /*确认*/
                : messages("common.submit") /*提交*/
            }
          </Button>
          <Button
            onClick={() => {
              this.props.closeFun();
            }}
          >
            {messages("common.cancel")}
          </Button>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    isOldCompany: state.login.isOldCompany,
  };
}

const WrappedEditLoan = Form.create()(NewRepayment);

export default connect(mapStateToProps)(WrappedEditLoan);
